<template>
  <div class="h-[37vh]">
    <CommonCard title="预警趋势">
      <template #content>
        <div>
          <TabBox :tab-list="tabList" @tab-handle="tabHandle" />
          <div ref="zxChart" class="w-full h-[240px]"></div>
        </div>
      </template>
    </CommonCard>
  </div>
</template>
<script lang="ts" setup>
import { getwarningTrend } from '@/api/home'
import CommonCard from '@/components/CommonCard.vue'
import TabBox from '@/components/TabBox.vue'
import { useCommonStore } from '@/stores/common'
import { timeNum } from '@/utils/commonFn'
import * as echarts from 'echarts'
import { markRaw, onMounted, onUnmounted, ref, watch } from 'vue'
const tabList = ref<CommonTypes.tabList[]>([
  {
    value: 'day',
    name: '今日'
  },
  {
    value: 'week',
    name: '近7天'
  },
  {
    value: 'month',
    name: '近30天'
  }
])
const tabHandle = (e: CommonTypes.tabList) => {
  console.log(e)
  formData.value.type = e.value
  initEchart()
}

const zxChart = ref(null)
const myChart = ref()
const timer = ref()
const option = ref<echarts.EChartsOption>({
  xAxis: {
    type: 'category',
    data: []
  },

  yAxis: {
    type: 'value',
    splitLine: {
      //坐标轴在grid区域中的分割线
      show: true,
      lineStyle: {
        color: '#51586c',
        type: 'dashed'
      }
    }
  },
  grid: {
    left: 0,
    right: 0,
    bottom: 0,
    top: 15,
    containLabel: true //是否包含坐标值
  },
  tooltip: {
    trigger: 'axis'
  },
  series: [
    {
      data: [],
      type: 'line',
      symbol: 'circle',
      symbolSize: 0,
      smooth: true,
      color: '#048BFF',
      areaStyle: {}
    }
  ]
})
onMounted(() => {
  myChart.value = markRaw(echarts.init(zxChart.value))
  initEchart()
  timer.value = setInterval(() => {
    initEchart()
  }, timeNum)
})

onUnmounted(() => {
  clearInterval(timer.value)
})
const formData = ref({
  institutionId: sessionStorage.getItem('institutionId'),
  type: 'day'
})
watch(
  () => useCommonStore().institutionId,
  (value) => {
    formData.value.institutionId = value
    initEchart()
  }
)
const initEchart = async () => {
  const res: any = await getwarningTrend(formData.value)
  let xData: string[] = []
  let ydata: string[] = []
  res.data.forEach((item: any) => {
    xData.push(item.date)
    ydata.push(item.count)
  })
  let obj: any = option.value
  obj.xAxis.data = xData as never
  obj.series[0].data = ydata as never
  myChart.value.setOption(option.value)
  window.onresize = function () {
    myChart.value.resize()
  }
}
</script>

<style scoped></style>
